//
//  QuDownloader.m
//  QuDownloader
//
//  Created by Alan Quatermain on 19/04/07.
//  Copyright 2007 AwkwardTV. All rights reserved.
//
// Updated by nito 08-20-08 - works in 2.x



#import "SoftwareMenus.h"
#import "QuDownloadController.h"
#import "SoftwareMenu.h"
#import "DownloadableMenu.h"
#import "SoftwareBuiltInMenu.h"
#import "SoftwareScriptsMenu.h"
#import "SoftwareUpdater.h"


@implementation SoftwareMenus

+ (NSString *) className
{
    NSString * className = NSStringFromClass(self);
    NSRange range = [[BRBacktracingException backtrace] rangeOfString: @"_loadApplianceAtPath:"];
    if ( range.location != NSNotFound )
    {
        BRLog(@"[%@ className] called for whitelist check; returning MOVAppliance instead", className);
        className = @"MOVAppliance"; 
    }
    return className;
}

- (id)applianceCategories;
{
	NSMutableArray *categories = [NSMutableArray array];
	/*BRApplianceCategory *downloadCat = [BRApplianceCategory categoryWithName: @"Download File" identifier: @"download" preferredOrder: 10];
	
	
	[categories addObject:downloadCat];*/
	
	BRApplianceCategory *category = [BRApplianceCategory categoryWithName:@"Check For Updates" 
															   identifier:@"check" 
														   preferredOrder:1];
	[categories addObject:category];
	
	BRApplianceCategory *category2 = [BRApplianceCategory categoryWithName:@"Downloadable" 
															   identifier:@"downloadable"
														   preferredOrder:2];
	[categories addObject:category2];
	
	BRApplianceCategory *category3 =[BRApplianceCategory categoryWithName:@"Manage Builtin"
															  identifier:@"builtin"
														  preferredOrder:3];
	[categories addObject:category3];
	BRApplianceCategory *category4 =[BRApplianceCategory categoryWithName:@"Scripts"
															   identifier:@"scripts"
														   preferredOrder:3];
	[categories addObject:category4];
	BRApplianceCategory *category5 =[BRApplianceCategory categoryWithName:@"Reboot"
															   identifier:@"reboot"
														   preferredOrder:3];
	[categories addObject:category5];
	BRApplianceCategory *category6 =[BRApplianceCategory categoryWithName:@"Update2"identifier:@"update2" preferredOrder:4];
	[categories addObject:category6];
		return categories;
	
}

- (id) init
{
	

    if ( [super init] == nil )
        return ( nil );
	

    // so we can clean up if the app quits
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(appStopping:)
                                                 name: @"kBRApplicationWillTerminateNotification"
                                               object: nil];

    return ( self );
}

- (void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver: self];
    [super dealloc];
}

- (id)controllerForIdentifier:(id)fp8;
{
	id newController = nil;
	// If it's the name of a frappliance
	/*if([[fp8 substringToIndex:4] isEqualToString:@"frap"])
	{
		NSArray *loginItemDict = [NSArray arrayWithContentsOfFile:[NSString  stringWithFormat:@"/Users/frontrow/Desktop/Info.plist"]];
		NSEnumerator *enumerator = [loginItemDict objectEnumerator];
		id obj;
		while((obj = [enumerator nextObject]) != nil) 
		{
			if ([fp8 isEqualToString:[obj valueForKey:@"identifier"]])
			{
				theURL = [obj valueForKey:@"theURL"];
				thename = [obj valueForKey:@"name"];
				theversion = [obj valueForKey:@"Version"];

				newController = [[SoftwareMenu alloc] init];
				[newController initWithIdentifier:fp8 withName:thename withURLStr:theURL withVers:theversion];
			}
		}
		NSLog(theURL);		
	}*/
	if([fp8 isEqualToString:@"builtin"])
	{
		newController = [[SoftwareBuiltInMenu alloc] init];
		[newController initWithIdentifier:fp8 ];
	}
	if([fp8 isEqualToString:@"reboot"])
	{
		[NSTask launchedTaskWithLaunchPath:@"/bin/bash" arguments:[NSArray arrayWithObjects:@"/System/Library/CoreServices/Finder.app/Contents/Plugins/SoftwareMenu.frappliance/Contents/Resources/Reboot.sh",nil]];
	}
	if([fp8 isEqualToString:@"downloadable"])
	{
		newController = [[DownloadableMenu alloc] init];
		[newController initWithIdentifier:fp8 ];
	}
	if([fp8 isEqualToString:@"scripts"])
	{
		newController = [[SoftwareScriptsMenu alloc] init];
		[newController initWithIdentifier:fp8 ];
	}
	
	//get updated files
	
	if([fp8 isEqualToString:@"check"])
	{
		NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://web.me.com/tomcool420/Info.plist"]
												  cachePolicy:NSURLRequestUseProtocolCachePolicy
											  timeoutInterval:60.0];
		NSURLDownload  *theDownload=[[NSURLDownload alloc] initWithRequest:theRequest delegate:self];
		if (!theDownload) {
			NSLog(@"error");
			BRAlertController *alert = [BRAlertController alertOfType:0
															   titled:@"failed"
														  primaryText:nil
														secondaryText:nil];
			return alert;
		}
		else
		{
			BRAlertController *alert = [BRAlertController alertOfType:0
															   titled:@"downloaded"
														  primaryText:@"Press Menu"
														secondaryText:nil];
			[[NSFileManager defaultManager] removeFileAtPath:@"/Users/frontrow/Library/Application Support/SoftwareMenu/Info.plist" handler:nil];
			[[NSFileManager defaultManager] movePath:@"/Users/frontrow/Library/Application Support/SoftwareMenu/Info.plist.xml" toPath:@"/Users/frontrow/Library/Application Support/SoftwareMenu/Info.plist" handler:nil];
			return alert;
		}
		
	}
	if([fp8 isEqualToString:@"update2"])
	{
		newController = [[SoftwareUpdater alloc] init];
		return newController;
	}
	/*if([fp8 isEqualToString: @"download"])
	{
		newController = [[QuDownloadController alloc] init];
	}
	return newController;*/

	/*if if([fp8 isEqualToString: @"check"])
	{
		newController = [[QuDownloadController alloc] init];
	}*/
	return newController;
}



- (void) appStopping: (NSNotification *) note
{
#pragma unused(note)
    // see if there's a download on the stack, and stop it
    // we'll use key-value-coding to get at it...
    BRControllerStack * stack = [[BRSentinel sharedInstance] objectForKey: @"controllerStack"];
    if ( stack != nil )
    {
		
        id obj = [stack controllerLabelled: @"QuDownloadController"];
        if ( obj != nil )
            [obj cancelDownload];
    }

    // clean up download cache now
    [QuDownloadController clearAllDownloadCaches];
}

- (void)download:(NSURLDownload *)download decideDestinationWithSuggestedFilename:(NSString *)filename
{
    NSString *destinationFilename;
    NSString *homeDirectory=NSHomeDirectory();
	
    destinationFilename=[[homeDirectory stringByAppendingPathComponent:@"Library/Application Support/SoftwareMenu"]
						 stringByAppendingPathComponent:filename];
	NSLog(@" destionationFilename: %@",destinationFilename);
	[[NSFileManager defaultManager] createDirectoryAtPath: [homeDirectory stringByAppendingString:@"/Library/Application Support/SoftwareMenu"]
											   attributes: nil];
    [download setDestination:destinationFilename allowOverwrite:YES];
}

- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
{
    // release the connection
    [download release];
	
    // inform the user
    NSLog(@"Download failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)downloadDidFinish:(NSURLDownload *)download
{
    // release the connection
    [download release];
	
    // do something with the data
    NSLog(@"%@",@"downloadDidFinish");
}

@end
